package com.example.springbgootjwt.util;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestControllerAdvice(annotations = {Controller.class, RestController.class})
public class ControlleAdviceUtil {

    @ExceptionHandler(Exception.class)   //如果定义了具体异常就只执行具体异常
    public String errorHandler(Exception e){
        return "异常";
    }

    @ExceptionHandler(ArithmeticException.class)
    public String errorHandler(ArithmeticException e){
        return "除0异常";
    }

    @ExceptionHandler(NullPointerException.class)
    public String errorHandler(NullPointerException e){
        return "空指针异常";
    }

    @ModelAttribute
    public String modelAttribute1(){
        return "hello world";
    }

    @ModelAttribute(name = "info")
    public String modelAttribute2(){
        return "hello world";
    }

    @ModelAttribute(name = "message")
    public String modelAttribute3(){

        String message ="hello world";
        return message;
    }

    @InitBinder("exceptionClass")
    public void bindExceptionClass(WebDataBinder binder){
        binder.setFieldDefaultPrefix("exceptionClass.");
    }

    @InitBinder("user")
    public void bindUser(WebDataBinder binder){
        binder.setFieldDefaultPrefix("user.");
    }

    @InitBinder
    public void bindDate(WebDataBinder binder){
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binder.registerCustomEditor(Date.class,new CustomDateEditor(simpleDateFormat,false));
    }
}
